package part.f;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.util.concurrent.Semaphore;

public class ClientConnection implements Runnable {

	private Socket client;
	private Semaphore sem;
	private int connectionNo;
	private EchoServer server;

	public ClientConnection(Socket socket) {
		client = socket;
		sem = null;
	}

	public ClientConnection(Socket socket, Semaphore sem) {
		client = socket;
		this.sem = sem;
	}

	public ClientConnection(Socket socket, int connectionNo, EchoServer server) {
		client = socket;
		this.connectionNo = connectionNo;
		this.server = server;
		sem = null;
	}

	public void run() {
		try {
			DataInputStream input;
			DataOutputStream output;

			byte[] buffer = new byte[2048];
			int bytesRead;

			input = new DataInputStream(client.getInputStream());
			output = new DataOutputStream(client.getOutputStream());
			bytesRead = input.read(buffer);

			while (bytesRead != -1) {
				output.writeBytes(connectionNo + "."
						+ server.getMessageNumber() + ": ");
				output.write(buffer, 2, bytesRead - 2);
				bytesRead = input.read(buffer);
			}
			client.close();
			if (sem != null) {
				sem.release();
			}
		} catch (IOException ioe) {
			System.out.println(ioe.getMessage());
		}
	}
}
